package pers.qianyu.module.image.provider.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import pers.qianyu.module.core.domain.image.model.baiduai.BaiduAccessTokenResult;
import pers.qianyu.module.core.domain.image.model.baiduai.BaiduImageCensorResult;
import pers.qianyu.module.image.properties.BaiduAiProperties;
import pers.qianyu.module.image.provider.IImageCensorProvider;

import java.time.Duration;
import java.util.Objects;

/**
 * @author mizzle rain
 * @date 2021-05-11 18:19
 */
@Service("iImageCensorProvider")
public class BaiduImageCensorProviderImpl implements IImageCensorProvider {
    @Autowired
    private BaiduAiProperties baiduAiProperties;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String IMAGE_CENSOR_URL = "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token={}";
    private static final String GET_ACCESS_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}";
    private static final String ACCESS_TOKEN_PREFIX = "access_token:baidu";
    private static final String TEMP_FILE_PATH = "_temp/";

    @Override
    public BaiduAccessTokenResult getAccessToken() {
        HttpRequest req = HttpUtil.createGet(StrUtil.format(GET_ACCESS_TOKEN_URL,
                baiduAiProperties.getApiKey(), baiduAiProperties.getSecretKey()));
        HttpResponse res = req.execute();
        String content = res.body();
        JSON json = JSONUtil.parse(content);
        Object error = json.getByPath("error");
        if (Objects.nonNull(error)) {
            return null;
        } else {
            return JSONObject.parseObject(content, BaiduAccessTokenResult.class, Feature.IgnoreNotMatch);
        }
    }

    @Override
    public BaiduImageCensorResult getImageCensorResult(String imageUrl) {
        BaiduAccessTokenResult accessTokenResult = (BaiduAccessTokenResult) redisTemplate.opsForValue().get(ACCESS_TOKEN_PREFIX);
        if (Objects.isNull(accessTokenResult)) {
            accessTokenResult = getAccessToken();
            redisTemplate.opsForValue().set(ACCESS_TOKEN_PREFIX, accessTokenResult, Duration.ofSeconds(accessTokenResult.getExpiresIn()));
        }
        HttpResponse res = HttpUtil.createGet(imageUrl).execute();
        String b64Str = Base64.encode(res.bodyBytes());
        HttpRequest req = HttpUtil.createPost(StrUtil.format(IMAGE_CENSOR_URL, accessTokenResult.getAccessToken()));
        req.header("Content-Type", "application/x-www-form-urlencoded");
        req.form("image", b64Str);
//        req.form("imgUrl", imageUrl);
        req.form("imgType", 0);
        res = req.execute();
        return JSONObject.parseObject(res.body(), BaiduImageCensorResult.class,
                Feature.IgnoreNotMatch);
    }
    /*
        百度图片检测规则
        大于等于5kb，小于等于4M，
        最短边大于等于128像素，
        小于等于4096像素，
        imageSize >= 5 * 1024
        imageSize <= 4 * 1024 * 1024
        imageWidth >= 128px
        imageWidth <= 4096px
     */
}
